package Servlets;

import Negocio.AdminDB;
import Negocio.Cliente;
import Negocio.MessageLogger;
import Negocio.ObjetoDB;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author sabidosan
 */
public class ListadoClientes extends BaseServlet {

    RequestDispatcher rd;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
    */

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
        {

        HttpSession s = request.getSession(true);
        Cookie[] cookies = request.getCookies();
        MessageLogger ml = new MessageLogger(getServletContext());
        boolean login = false;
        
        for(int i=0; i<cookies.length; i++) {
          Cookie cookie = cookies[i];
          if (cookie.getName().equals("login") && cookie.getValue().equals("true"))
            login=true;
        }
      
        
        if(login){
            AdminDB adb = new AdminDB();
            ObjetoDB o = new ObjetoDB();
            Cliente cl = new Cliente();
            List<Cliente> clientes = null;

            String boton = request.getParameter("borrar");
            if(boton==null) boton = request.getParameter("guardar");

            if(boton!=null)
            {
                o.setTabla("Cliente");
                boolean valid=false;
                boolean empty=true;

                if(boton.equalsIgnoreCase("Guardar")){
                    if(request.getParameter("nombre")!=null) {o.addCampo("nombre",request.getParameter("nombreCliente"));empty=false;}
                    if(request.getParameter("apellido")!=null) {o.addCampo("apellido",request.getParameter("apellidoCliente"));empty=false;}
                    if(request.getParameter("nick")!=null) {o.addCampo("nick",request.getParameter("nickCliente"));empty=false;}            
                    if(request.getParameter("password")!=null) {o.addCampo("password",request.getParameter("passwordCliente"));empty=false;}
                    if(request.getParameter("genero")!=null) {o.addCampo("genero",request.getParameter("generoCliente"));empty=false;}

                    if(!empty){
                        try {
                            o.setId(adb.getID("Cliente", "email='"+request.getParameter("hiddenEmail")+"'"));
                            valid = adb.actualizar(o);
                            ml.log("'Admin' - datos de cliente ("+request.getParameter("hiddenEmail")+") modificados");
                        } catch (Exception ex) {
                            Logger.getLogger("Actualizar Cliente").log(Level.SEVERE, null, ex);
                            ml.log("'Admin' - fallo actualizando datos de cliente ("+cl.getEmail()+")");
                        }
                    }
                    else valid=true;
                }
                else if (boton.equalsIgnoreCase("Borrar")){
                    System.out.println("borrar");
                    
                        Cliente c = new Cliente();
                    try {
                        c.setEmail(request.getParameter("hiddenEmail"));
                        valid = c.borrar();
                        ml.log("'Admin' - cliente ("+c.getEmail()+") eliminado");
                    } catch (Exception ex) {
                        Logger.getLogger("Borrar Cliente").log(Level.SEVERE, null, ex);
                        ml.log("'Admin' - fallo eliminando el cliente ("+c.getEmail()+")");
                    }
                }        

                if (valid==true) {
                    try {
                    clientes = cl.getAllClientes(adb.getConnection());
                } catch (SQLException ex) {
                    Logger.getLogger(ListadoClientes.class.getName()).log(Level.SEVERE, null, ex);
                }
                    s.setAttribute("listaDeClientes", clientes);
                   dispatch("/listaClientes.jsp", request, response);
                } else {
                    dispatch("/404.jsp", request, response);
                }
            }
            else{
                    try {
                    clientes = cl.getAllClientes(adb.getConnection());
                } catch (SQLException ex) {
                    Logger.getLogger(ListadoClientes.class.getName()).log(Level.SEVERE, null, ex);
                }
                s.setAttribute("listaDeClientes", clientes);
                ml.log("'Admin' - listado de clientes");
                dispatch("/listaClientes.jsp", request, response);
            }
        }
        else dispatch("/index.jsp", request, response);
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
